import json

from flask import jsonify, make_response, request, g
from flask_jwt_extended import get_jwt_identity
from flask_restful import Resource
from sqlalchemy import text
from sqlalchemy.orm import aliased

from apps.model.serializeModel import model_to_list, model_to_dict
from apps.settingApi.api.basic.model import basicDataModel
from apps.settingApi.api.chart.utils import chartDbJonOne, chartDbListJon
from apps.settingApi.switchCase.casePrimaryKey import caseGetPrimaryKeyData
from apps.settingApi.switchCase.serializeParameter import serializeGetFilter, pageResultData, getArgsData, \
    serializeParData

from apps.settingApi.switchCase.settingCurd import getPk, deletePk, putPk, getList
from apps.settingApi.api.chart.model import chartModel, chartDataModel
from apps.settingApi.utils import getDataTime
from comm.dbConnect import get_yun_session, dbJonOne
from comm.sqlalchemyConfig import db
from comm.decorator import login_required
from apps.settingApi.utils import getLessees

chartViewModel = chartModel

class chartListView(Resource):
    # 查询列表
    @login_required()
    def get(self):
        # 获取所有的参数
        serializeFilterList, args = serializeGetFilter(chartViewModel)
        serializeFilterList.append(chartViewModel.lessees_id==g.lessees_id)
        modelDataObj = chartViewModel.query.filter(*serializeFilterList).order_by(
            chartViewModel.id.asc()).paginate(page=args['page'], per_page=args['pageSize'], error_out=False)
        objData = pageResultData(modelDataObj)
        result = model_to_list(modelDataObj, [])
        objData["data"] = result  # 分页数据
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)
class chartPkView(Resource):
    # @login_required()
    def get(self, pk):
        result = chartViewModel.query.filter(chartViewModel.id == pk).first()
        if result == None:
            return make_response(jsonify({'msg': '数据不存在'}), 202)
        objData = {}
        objData['id'] = result.id
        objData['name'] = result.name
        objData['type'] = result.type
        objData['config'] = json.loads(result.config)
        # 查询配置数据仓库，与连接池
        for itm in objData['config']['topList']:
            for itm1 in itm['config']:
                if itm1['pool'] !='':
                    poolData = basicDataModel.query.filter(basicDataModel.id == itm1['pool']).first()
                    if poolData!=None:
                        itm1['pool_name'] = poolData.value
                if itm1['wh']!='':
                    whData = chartDataModel.query.filter(chartDataModel.id == itm1['wh']).first()
                    if whData!='':
                        itm1['wh_name'] = whData.name
                        itm1['sql'] = whData.sql
                        itm1['pool'] = whData.pool
                        poolData1 = basicDataModel.query.filter(basicDataModel.id == whData.pool).first()
                        if poolData1 != None:
                            itm1['pool_name'] = poolData1.value
        for itm in objData['config']['bottomList']:
            for itm1 in itm['config']:
                if itm1['pool'] !='':
                    poolData = basicDataModel.query.filter(basicDataModel.id == itm1['pool']).first()
                    if poolData!=None:
                        itm1['pool_name'] = poolData.value
                if itm1['wh']!='':
                    whData = chartDataModel.query.filter(chartDataModel.id == itm1['wh']).first()
                    if whData!='':
                        itm1['wh_name'] = whData.name
                        itm1['sql'] = whData.sql
                        itm1['pool'] = whData.pool
                        poolData1 = basicDataModel.query.filter(basicDataModel.id == whData.pool).first()
                        if poolData1 != None:
                            itm1['pool_name'] = poolData1.value

        objData['create_user'] = result.create_user
        objData['create_time'] = result.create_time
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def put(self, pk):
        # 获取所有参数
        args, err = getArgsData()
        config = args.get('config',None)
        name = args.get('name',None)

        exist = chartViewModel.query.filter(chartViewModel.id == pk,chartViewModel.lessees_id==g.lessees_id).first()
        if exist is None:
            return make_response(jsonify({'msg': '数据不存在'}), 202)

        if exist.type==1:
            return make_response(jsonify({'msg': '系统模板禁止修改'}), 202)

        updata = {}
        if config!='' and config !=None:
            updata['config'] = json.dumps(config, ensure_ascii=False)
        if name!='' and name !=None:
            updata['name'] = name
        chartViewModel.query.filter(chartViewModel.id == pk).update(updata)
        print(updata)
        objData, err = putPk(chartViewModel, pk, updata)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)
        newData = chartViewModel.query.filter(chartViewModel.id == pk).first()
        objData = model_to_dict(newData, [])
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def post(self, pk):
        args = request.get_json()
        name = args.get('name',None)
        rem = args.get('rem',None)
        if name=='' or name is None:
            return make_response(jsonify({'msg': '看板名称不能为空'}), 202)
        result = chartViewModel.query.filter(chartViewModel.id == pk).first()
        if result == None:
            return make_response(jsonify({'msg': '数据不存在'}), 202)
        addData = {}
        addData["id"] = caseGetPrimaryKeyData()
        addData["name"] = name
        addData["rem"] = rem
        addData["type"] = 2
        addData["config"] = result.config
        addData["create_user"] = g.user_id
        addData['lessees_id'] = g.lessees_id
        try:
            add = chartViewModel(**addData)
            db.session.add(add)
            db.session.commit()
            db.session.flush()
            objData = model_to_dict(add, [])
        except Exception as e:
            return make_response(jsonify({'msg': '克隆失败' + repr(e)}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def delete(self, pk):
        # 查询数据
        result = chartViewModel.query.filter(chartViewModel.id == pk,chartViewModel.lessees_id==g.lessees_id).first()
        if result == None:
            return make_response(jsonify({'msg': '数据不存在'}), 202)
        if result.type == 1 :
            return make_response(jsonify({'msg': '模板看板禁止删除'}), 202)
        resultData = model_to_dict(result, [])
        try:
            deletedata = db.session.query(chartViewModel).filter(chartViewModel.id == pk).first()
            db.session.delete(deletedata)
            db.session.commit()
        except Exception as e:
            return make_response(jsonify({'msg': '数据删除失败' + repr(e)}), 202)
        return make_response(jsonify({'msg': '成功', 'result': resultData}), 200)

class chartGetDataListView(Resource):

    def post(self):
        # 校验数据库是否能连接成功
        args = request.get_json()
        pool = args.get('pool',None)
        components = args.get('components',None)
        sql = args.get('sql',None)
        if pool =='' or pool == None:
            return make_response(jsonify({'msg': '连接池不能为空'}), 202)

        if sql =='' or sql == None:
            return make_response(jsonify({'msg': '数据源不能为空'}), 202)

        if components =='' or components == None:
            return make_response(jsonify({'msg': '组件不能为空'}), 202)

        # 查询连接池配置
        dbpool, err = basicDataModel.getPoolPk(pool)
        if err != None:
            return make_response(jsonify({'msg': err}), 202)

        if components in ('panel'):
            print('进入查询单个')
            data ,err = chartDbJonOne(sql=sql,dbpool=dbpool)
            if err !=None:
                return make_response(jsonify({'msg': err}), 202)
            print(data)
        else:
            print('进入查询列表')
            data, err = chartDbListJon(sql=sql, dbpool=dbpool)
            if err != None:
                return make_response(jsonify({'msg': err}), 202)
        return make_response(jsonify({'msg': '成功', 'result': data}), 200)


class chartDataListView(Resource):
    # 查询列表
    @login_required()
    def get(self):
        # 获取所有的参数
        serializeFilterList, args = serializeGetFilter(chartDataModel)
        serializeFilterList.append(chartDataModel.lessees_id == g.lessees_id)
        filedList = [
            chartDataModel.id,
            chartDataModel.name,
            chartDataModel.componentName,
            chartDataModel.sql,
            chartDataModel.pool,
            chartDataModel.rem,
            chartDataModel.create_user,
            chartDataModel.create_time,
            chartDataModel.lessees_id,
            basicDataModel.value.label('pool_name')
        ]
        modelDataObj = db.session.query(*filedList).outerjoin(basicDataModel, chartDataModel.pool == basicDataModel.id).filter(*serializeFilterList).order_by(
        chartDataModel.id.asc()).paginate(page=args['page'], per_page=args['pageSize'], error_out=False)
        objData = pageResultData(modelDataObj)
        result = model_to_list(modelDataObj, [])
        objData["data"] = result  # 分页数据
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

    @login_required()
    def post(self):
        args = request.get_json()
        componentName = args.get('componentName', None)
        pool = args.get('pool', None)
        name = args.get('dataName', None)
        sql = args.get('sql', None)
        rem = args.get('rem', None)
        if componentName == '' or componentName is None:
            return make_response(jsonify({'msg': '组件模板不为空'}), 202)
        if pool == '' or pool is None:
            return make_response(jsonify({'msg': '连接池不能为空'}), 202)
        if name == '' or name is None:
            return make_response(jsonify({'msg': '数据名称不能为空'}), 202)
        if sql == '' or sql is None:
            return make_response(jsonify({'msg': '数据源不能为空'}), 202)
        addData = {}
        addData["id"] = caseGetPrimaryKeyData()
        addData["componentName"] = componentName
        addData["pool"] = pool
        addData["name"] = name
        addData["sql"] = sql
        addData["rem"] = rem
        addData["create_user"] = g.user_id
        addData['lessees_id'] = g.lessees_id
        try:
            add = chartDataModel(**addData)
            db.session.add(add)
            db.session.commit()
            db.session.flush()
            objData = model_to_dict(add, [])
        except Exception as e:
            return make_response(jsonify({'msg': '新增失败' + repr(e)}), 202)
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)

class chartDataPkView(Resource):
    @login_required()
    def get(self, pk):
        result = chartDataModel.query.filter(chartDataModel.id == pk, chartDataModel.lessees_id == g.lessees_id).first()
        if result == None:
            return make_response(jsonify({'msg': '数据不存在'}), 202)
        # 查询连接池

        poolData = basicDataModel.query.filter(basicDataModel.id == result.pool, basicDataModel.lessees_id == g.lessees_id).first()
        if poolData == None:
            return make_response(jsonify({'msg': '数据异常连接池不存在'}), 202)
        resultData = {}
        resultData["componentName"] = result.componentName
        resultData["pool"] = result.pool
        resultData["poolName"] = poolData.value
        resultData["dataName"] = result.name
        resultData["rem"] = result.rem
        resultData["sql"] = result.sql

        return make_response(jsonify({'msg': '成功', 'result': resultData}), 200)

    @login_required()
    def put(self, pk):
        args, err = getArgsData()
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)
        argsData = {}
        if args.get('dataName',None)!=None:
            argsData['name'] = args['dataName']
        if args.get('pool',None)!=None:
            argsData['pool'] = args['pool']
        if args.get('rem',None)!=None:
            argsData['rem'] = args['rem']
        if args.get('sql',None)!=None:
            argsData['sql'] = args['sql']
        addData, err = serializeParData(model=chartDataModel, argsData=argsData)
        if err != None:
            return make_response(jsonify({'msg': err, }), 202)
        # 判断数据是否存在
        exit_z = db.session.query(chartDataModel).filter(chartDataModel.id == pk).first()
        if exit_z == None:
            return make_response(jsonify({'msg': '数据不存在', }), 202)
        print(pk)
        addr = chartDataModel.query.filter(chartDataModel.id == pk).with_for_update().first()
        for itm in addData.keys():
            setattr(addr, itm, addData[itm])
        db.session.commit()
        # 获取更新的数据
        update = chartDataModel.query.filter(chartDataModel.id == pk).first()
        if update is None:
            return None, '获取更新后的数据失败'
        objData = model_to_dict(update, [])
        return make_response(jsonify({'msg': '成功', 'result': objData}), 200)
    @login_required()
    def delete(self, pk):
        # 查询数据
        result = chartDataModel.query.filter(chartDataModel.id == pk, chartDataModel.lessees_id == g.lessees_id).first()
        if result == None:
            return make_response(jsonify({'msg': '数据不存在'}), 202)
        resultData = model_to_dict(result, [])
        try:
            deletedata = db.session.query(chartDataModel).filter(chartDataModel.id == pk).first()
            db.session.delete(deletedata)
            db.session.commit()
        except Exception as e:
            return make_response(jsonify({'msg': '数据删除失败' + repr(e)}), 202)
        return make_response(jsonify({'msg': '成功', 'result': resultData}), 200)